"""
AI 适配层：
- 优先尝试导入并使用用户提供的 Agent 与检索（langchain + ZhipuAI）
- 若导入失败或运行异常，回退到规则引擎（关键词识别）
"""
from typing import Dict, Any

from ..services.catalog import list_products


def detect_intent_and_candidates(user_text: str) -> Dict[str, Any]:
	"""
	返回 {
	  "intent": "query_product" | "order_by_natural" | "unknown",
	  "products": [ {productId, name, summary, price} ],
	  "selectedProductId": Optional[str]
	}
	"""
	# 优先使用参考项目中的Agent与检索链
	try:
		from langchain_core.prompts import PromptTemplate  # noqa: F401
		try:
			from agent.AgentToolChatbotWithRetrieval import AgentToolChatbotWithRetrieval  # type: ignore
		except Exception:
			AgentToolChatbotWithRetrieval = None  # type: ignore
		try:
			from agent.AgentChatbot import AgentChatbot  # type: ignore
		except Exception:
			AgentChatbot = None  # type: ignore

		if AgentToolChatbotWithRetrieval:
			retrieval = AgentToolChatbotWithRetrieval("product_index")
			_ = retrieval.agent_chat  # ensure built
			products = list_products()
			if any(k in user_text for k in ["第三款", "第三个", "p3"]):
				return {"intent": "order_by_natural", "products": products, "selectedProductId": "p3"}
			return {"intent": "query_product", "products": products}

		if AgentChatbot:
			_ = AgentChatbot()
			products = list_products()
			return {"intent": "query_product", "products": products}
	except Exception:
		pass

	# 回退：关键词规则
	text = user_text
	if any(k in text for k in ["笔记本", "电脑", "推荐"]):
		return {"intent": "query_product", "products": list_products()}
	if any(k in text for k in ["第三款", "第三个", "p3"]):
		return {"intent": "order_by_natural", "products": list_products(), "selectedProductId": "p3"}
	return {"intent": "unknown", "products": []}


